import type React from 'react'
import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTheme } from '../../theme'
import styles from './Select.module.less'

export interface SelectOption {
  value: string | number
  label: string
  disabled?: boolean
}

export interface SelectProps {
  options: SelectOption[]
  value?: string | number
  defaultValue?: string | number
  placeholder?: string
  disabled?: boolean
  className?: string
  onChange?: (value: string | number) => void
  variant?: 'primary' | 'secondary' | 'outline'
  size?: 'small' | 'medium' | 'large'
  glow?: boolean
}

const Select: React.FC<SelectProps> = ({
  options,
  value,
  defaultValue,
  placeholder = '请选择',
  disabled = false,
  className,
  onChange,
  variant = 'primary',
  size = 'medium',
  glow = false,
}) => {
  const { theme, themeName } = useTheme()
  const [isOpen, setIsOpen] = useState(false)
  const [selectedValue, setSelectedValue] = useState<string | number | undefined>(
    value !== undefined ? value : defaultValue
  )
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 })
  const selectRef = useRef<HTMLDivElement>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node
      if (
        selectRef.current &&
        !selectRef.current.contains(target) &&
        dropdownRef.current &&
        !dropdownRef.current.contains(target)
      ) {
        setIsOpen(false)
      }
    }

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
      return () => {
        document.removeEventListener('mousedown', handleClickOutside)
      }
    }
  }, [isOpen])

  useEffect(() => {
    if (value !== undefined && value !== selectedValue) {
      setSelectedValue(value)
    }
  }, [value, selectedValue])

  const handleToggle = () => {
    if (!disabled) {
      if (!isOpen && selectRef.current) {
        const rect = selectRef.current.getBoundingClientRect()
        console.log('Select toggle - rect:', rect)

        // 根据不同的 size 调整间距
        const getMarginBySize = (size: string) => {
          switch (size) {
            case 'small':
              return 3
            case 'medium':
              return 5
            case 'large':
              return 8
            default:
              return 5
          }
        }

        const margin = getMarginBySize(size)
        const position = {
          top: rect.bottom + window.scrollY + margin,
          left: rect.left + window.scrollX,
          width: rect.width,
        }
        console.log('Select toggle - calculated position:', position, 'margin:', margin)
        setDropdownPosition(position)
      }
      setIsOpen(!isOpen)
    }
  }

  const handleSelect = (optionValue: string | number) => {
    console.log('Select option clicked:', optionValue)
    setSelectedValue(optionValue)
    setIsOpen(false)
    if (onChange) {
      onChange(optionValue)
    }
  }

  const getSelectedLabel = () => {
    if (selectedValue !== undefined) {
      const selectedOption = options.find((option) => option.value === selectedValue)
      return selectedOption ? selectedOption.label : placeholder
    }
    return placeholder
  }

  const classNames = [
    styles.select,
    styles[variant],
    styles[size],
    styles[`theme-${themeName}`],
    isOpen && styles.open,
    disabled && styles.disabled,
    glow && styles.glow,
    className,
  ]
    .filter(Boolean)
    .join(' ')

  const selectStyle = {
    '--theme-primary-gradient': theme.colors.primary.gradient,
    '--theme-secondary-gradient': theme.colors.secondary.gradient,
    '--theme-outline-border': theme.colors.outline.border,
    '--theme-primary-shadow': theme.colors.shadow.primary,
    '--theme-secondary-shadow': theme.colors.shadow.secondary,
    '--theme-glow-gradient': `linear-gradient(45deg, ${theme.colors.primary.light}, ${theme.colors.primary.main}, ${theme.colors.primary.dark}, ${theme.colors.primary.light})`,
    '--theme-primary-light': theme.colors.primary.light,
    '--theme-primary-main': theme.colors.primary.main,
    '--theme-secondary-text': theme.colors.text.secondary,
  } as React.CSSProperties

  const dropdownContent = isOpen ? (
    <div
      ref={dropdownRef}
      className={styles.selectDropdown}
      style={{
        position: 'absolute',
        top: `${dropdownPosition.top}px`,
        left: `${dropdownPosition.left}px`,
        width: `${dropdownPosition.width}px`,
        zIndex: 999999,
      }}
      onClick={() => console.log('Dropdown container clicked')}
    >
      <ul className={styles.selectOptions}>
        {options.map((option) => (
          <li
            key={option.value}
            className={`${styles.selectOption} ${
              option.disabled ? styles.disabled : ''
            } ${selectedValue === option.value ? styles.selected : ''}`}
            onClick={(e) => {
              console.log('Option clicked:', option.value, option.label)
              e.stopPropagation()
              e.preventDefault()
              if (!option.disabled) {
                handleSelect(option.value)
              }
            }}
            onMouseDown={(e) => {
              console.log('Option mouse down:', option.value)
              e.preventDefault()
            }}
            onMouseEnter={() => console.log('Option mouse enter:', option.value)}
          >
            {option.label}
          </li>
        ))}
      </ul>
    </div>
  ) : null

  return (
    <>
      <div className={classNames} style={selectStyle}>
        <div ref={selectRef} className={styles.selectHeader} onClick={handleToggle}>
          <span className={styles.selectValue}>{getSelectedLabel()}</span>
          <span className={`${styles.arrow} ${isOpen ? styles.up : ''}`} />
        </div>
      </div>
      {typeof document !== 'undefined' && createPortal(dropdownContent, document.body)}
    </>
  )
}

export default Select
